package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacades "github.com/hulutech-web/http_result"

	"goravel/app/models"
)

type ReadcmdController struct {
	//Dependent services
}

func NewReadcmdController() *ReadcmdController {
	return &ReadcmdController{
		//Inject services
	}
}

func (r *ReadcmdController) Index(ctx http.Context) http.Response {
	readcmds := []models.Readcmd{}
	queries := ctx.Request().Queries()
	result, _ := httpfacades.NewResult(ctx).SearchByParams(queries, map[string]interface{}{}).ResultPagination(&readcmds, "Protorule")
	return result
}

func (r *ReadcmdController) List(ctx http.Context) http.Response {
	readcmds := []models.Readcmd{}
	facades.Orm().Query().Model(&models.Readcmd{}).Find(&readcmds)
	return httpfacades.NewResult(ctx).Success("", readcmds)
}

func (r *ReadcmdController) Show(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt("id")
	var readCmd models.Readcmd
	facades.Orm().Query().Model(&models.Readcmd{}).With("Protorule").Where("id=?", id).First(&readCmd)
	return httpfacades.NewResult(ctx).Success("", readCmd)
}

func (r *ReadcmdController) Rule(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt("id")
	var readCmd models.Readcmd
	facades.Orm().Query().Model(&models.Readcmd{}).Where("id=?", id).Find(&readCmd)
	var protorule models.Protorule
	facades.Orm().Query().Model(&readCmd).Association("Protorule").Find(&protorule)
	if protorule.ID == 0 {
		ctx.Request().Bind(&protorule)

		//facades.Orm().Query().Model(&models.Protorule{}).Create(&protorule)
		facades.Orm().Query().Model(&readCmd).Association("Protorule").Append(&protorule)
	} else {
		ctx.Request().Bind(&protorule)

		facades.Orm().Query().Model(&models.Protorule{}).Delete(&models.Protorule{}, protorule.ID)
		facades.Orm().Query().Model(&models.Protorule{}).Create(&protorule)
		//关联创建或者更新
		facades.Orm().Query().Model(&readCmd).Association("Protorule").Append(&protorule)
	}

	return httpfacades.NewResult(ctx).Success("修改成功", nil)
}

func (r *ReadcmdController) Destory(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt("id")
	var readCmd models.Readcmd
	facades.Orm().Query().Model(&models.Readcmd{}).Where("id=?", id).First(&readCmd)
	facades.Orm().Query().Model(&readCmd).Association("Protorule").Delete(readCmd.Protorule)
	facades.Orm().Query().Model(&readCmd).Delete(&readCmd)
	return httpfacades.NewResult(ctx).Success("删除成功", nil)
}
